@extends('layouts.app')

@section('title', '自动定时记账')

@push('styles')
<style>
    /* 定时记账页面样式 */
    .account-books-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 20px;
        text-align: center;
        position: relative;
    }

    .account-books-title {
        font-size: 20px;
        font-weight: 600;
        margin: 0;
    }

    .auto-record-container {
        padding: 20px;
        max-width: 600px;
        margin: 0 auto;
        padding-bottom: 100px;
    }

    .add-record-section {
        margin-bottom: 30px;
    }

    .add-record-btn {
        width: 100%;
        padding: 15px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        border-radius: 12px;
        font-size: 16px;
        font-weight: 500;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        text-decoration: none;
    }

    .add-record-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
        color: white;
    }

    .records-list {
        display: flex;
        flex-direction: column;
        gap: 15px;
    }

    .record-item {
        background: white;
        border-radius: 12px;
        padding: 20px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;
        position: relative;
    }

    .record-item:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
    }

    .record-item.disabled {
        opacity: 0.6;
        background: #f8f9fa;
    }

    .record-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 12px;
    }

    .record-info {
        display: flex;
        align-items: center;
        gap: 12px;
        flex: 1;
    }

    .record-icon {
        width: 48px;
        height: 48px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
        color: white;
    }

    .record-icon.expense {
        background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
    }

    .record-icon.income {
        background: linear-gradient(135deg, #51cf66 0%, #40c057 100%);
    }

    .record-details {
        flex: 1;
    }

    .record-name {
        font-size: 16px;
        font-weight: 600;
        color: #2d3748;
        margin: 0 0 4px 0;
    }

    .record-amount {
        font-size: 18px;
        font-weight: 700;
        margin: 0 0 4px 0;
    }

    .record-amount.expense {
        color: #e53e3e;
    }

    .record-amount.income {
        color: #38a169;
    }

    .record-schedule {
        font-size: 12px;
        color: #718096;
        margin: 8px 0;
    }

    .record-category {
        font-size: 12px;
        color: #718096;
        margin: 4px 0;
    }

    .record-description {
        font-size: 12px;
        color: #a0aec0;
        margin: 4px 0;
    }

    .record-actions {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 12px;
    }

    .toggle-switch {
        position: relative;
        width: 44px;
        height: 24px;
        background: #cbd5e0;
        border-radius: 12px;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .toggle-switch.active {
        background: #667eea;
    }

    .toggle-switch::after {
        content: '';
        position: absolute;
        top: 2px;
        left: 2px;
        width: 20px;
        height: 20px;
        background: white;
        border-radius: 50%;
        transition: all 0.3s ease;
    }

    .toggle-switch.active::after {
        transform: translateX(20px);
    }

    .action-buttons {
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .action-btn {
        width: 32px;
        height: 32px;
        color: #718096;
        justify-content: center;
        font-size: 14px;
    }

    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #718096;
    }

    .empty-state-icon {
        font-size: 48px;
        margin-bottom: 16px;
    }

    .empty-state-title {
        font-size: 18px;
        font-weight: 600;
        margin-bottom: 8px;
        color: #4a5568;
    }

    .empty-state-desc {
        font-size: 14px;
        line-height: 1.5;
        color: #718096;
    }

</style>
@endpush

@section('content')
<div class="account-books-header">
    <button class="back-btn" onclick="window.location.href = '{{ route('user.books') }}'">‹</button>
    <h1 class="account-books-title">定时记账</h1>
</div>

<div class="auto-record-container">
    <div class="add-record-section">
        <a href="{{ route('auto-transaction.create') }}" class="add-record-btn">
            <i class="fas fa-plus"></i>
            <span>添加定时记账</span>
        </a>
    </div>

    <div class="records-list" id="autoRecordList">
        <!-- 定时记账列表将在这里动态生成 -->
    </div>

    <div class="empty-state" id="emptyState" style="display: none;">
        <div class="empty-state-icon">
            <i class="fas fa-clock"></i>
        </div>
        <div class="empty-state-title">还没有设置定时记账</div>
        <div class="empty-state-desc">设置定时记账后，系统会按照您的设定自动创建交易记录</div>
    </div>
</div>

<!-- 弹窗已移除，创建和编辑功能现在在新页面中进行 -->
@endsection

@push('scripts')
<script>
    $(document).ready(function() {
        // 加载定时记账列表
        loadAutoRecords();
    });

    // 加载定时记账列表
    function loadAutoRecords() {
        $.ajax({
            url: '{{ route("auto-transaction.data") }}',
            type: 'GET',
            data: {
                book_id: '{{ $book->id }}'
            },
            success: function(response) {
                if (response.success) {
                    renderAutoRecords(response.data);
                } else {
                    alert('加载失败：' + response.message);
                }
            },
            error: function(xhr) {
                alert('加载失败，请稍后重试');
                console.error(xhr);
            }
        });
    }

    // 渲染定时记账列表
    function renderAutoRecords(records) {
        const $list = $('#autoRecordList');
        $list.empty();

        if (records.length === 0) {
            $('#emptyState').show();
            return;
        }

        $('#emptyState').hide();

        records.forEach(function(record) {
            const $item = createRecordElement(record);
            $list.append($item);
        });
    }

    // 创建记录元素
    function createRecordElement(record) {
        const disabledClass = record.status === 0 ? 'disabled' : '';
        const amountClass = record.type === 1 ? 'income' : 'expense';
        const iconClass = record.type === 1 ? 'income' : 'expense';
        const toggleClass = record.status === 1 ? 'active' : '';

        // 格式化执行时间
        let scheduleText = '';
        switch (parseInt(record.period_type)) {
            case 1:
                scheduleText = '每天';
                break;
            case 2:
                scheduleText = `每周${formatWeekDay(record.period_value)}`;
                break;
            case 3:
                scheduleText = `每月${record.period_value}日`;
                break;
            case 4:
                scheduleText = '每年';
                break;
        }

        scheduleText += ` ${record.execute_time} 执行`;

        // 获取分类名称
        let categoryName = record.category_name;
        if (record.sub_category_name) {
            categoryName += ` - ${record.sub_category_name}`;
        }

        const $item = $(`
            <div class="record-item ${disabledClass}" data-id="${record.id}">
                <div class="record-header">
                    <div class="record-info">
                        <div class="record-icon ${iconClass}">
                            ${record.category_icon}
                        </div>
                        <div class="record-details">
                            <div class="record-name">${record.title}</div>
                            <div class="record-amount ${amountClass}">
                                ${record.type === 1 ? '+' : '-'} ¥${record.amount}
                            </div>
                            <div class="record-category">${categoryName}</div>
                            <div class="record-schedule">${scheduleText}</div>
                            ${record.description ? `<div class="record-description">${record.description}</div>` : ''}
                        </div>
                    </div>
                </div>
                <div class="record-actions">
                    <div class="toggle-switch ${toggleClass}" data-id="${record.id}">
                    </div>
                    <div class="action-buttons">
                        <a href="{{ route('auto-transaction.index', '') }}/${record.id}/edit" class="action-btn">✏️</a>
                        <button type="button" class="action-btn danger delete-btn" data-id="${record.id}">🗑️</button>
                    </div>
                </div>
            </div>
        `);

        return $item;
    }

    // 格式化星期几
    function formatWeekDay(value) {
        const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
        return weekDays[value] ? `${weekDays[value]}` : value;
    }

    // 编辑功能现在通过链接跳转到新页面，不再需要弹窗处理

    // 切换记录状态
    $(document).on('click', '.toggle-switch', function() {
        const recordId = $(this).data('id');
        const $item = $(this).closest('.record-item');
        const $toggle = $(this);

        $.ajax({
            url: `{{ route('auto-transaction.toggle-status', ['id' => ':id']) }}`.replace(':id', recordId),
            type: 'PATCH',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    if (response.status === 1) {
                        $item.removeClass('disabled');
                        $toggle.addClass('active');
                        showToast('已启用定时记账');
                    } else {
                        $item.addClass('disabled');
                        $toggle.removeClass('active');
                        showToast('已禁用定时记账');
                    }
                } else {
                    showError('保存失败，请稍后重试'. xhr.responseJSON);
                }
            },
            error: function(xhr) {
                showError(xhr.responseJSON.message || '操作失败，请稍后重试', xhr.responseJSON);
                console.error(xhr);
            }
        });
    });

    // 删除定时记账
    $(document).on('click', '.delete-btn', function() {
        const recordId = $(this).data('id');

        if (confirm('确定要删除这条定时记账吗？')) {
            $.ajax({
                url: `{{ route('auto-transaction.destroy', '') }}/${recordId}`,
                type: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function(response) {
                    if (response.success) {
                        loadAutoRecords();
                        showToast('自动记账已删除');
                    } else {
                        alert('删除失败：' + response.message);
                    }
                },
                error: function(xhr) {
                    alert('删除失败，请稍后重试');
                    console.error(xhr);
                }
            });
        }
    });

</script>
@endpush
